<template>
  <div class="login-view">
    <el-card class="login-card">
      <template #header>
        <div class="login-bar">
          <span
            class="login-title"
            :class="{ active: activeTab === 'common' }"
            @click="setActiveTab('common')"
            >用户登录</span
          >
          <span
            class="login-title"
            :class="{ active: activeTab === 'traffic' }"
            @click="setActiveTab('traffic')"
            >交管部门</span
          >
          <span
            class="login-title"
            :class="{ active: activeTab === 'admin' }"
            @click="setActiveTab('admin')"
            >管理员</span
          >
        </div>
      </template>

      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="name">
          <el-input
            v-model="loginForm.name"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="sliderValue">
          <div class="slider-container">
            <span class="slider-label">请滑动验证</span>
            <el-slider
              v-model="loginForm.sliderValue"
              :min="0"
              :max="100"
              :show-tooltip="false"
              @change="handleSliderChange"
              style="width: 250px"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <input type="checkbox" id="remember-me" class="mr-2" />
              <label for="remember-me">记住密码</label>
            </div>
            <a href="#" class="text-blue-500">忘记密码？</a>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="button-group">
            <el-button type="primary" @click="handleLogin" class="login-button">
              登录
            </el-button>
            <el-button
              @click="goToRegister"
              class="register-button"
              :disabled="isDisabled"
            >
              注册
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'
import request from '../utils/request'
import { useMainStore } from '../../stores/index'

const activeTab = ref('common')
const router = useRouter()
const isDisabled = ref(false)
const store = useMainStore()

/**
 * @description 登录表单数据
 */
const loginForm = reactive({
  name: '',
  password: '',
  sliderValue: 0,
})

/**
 * @description 表单验证规则
 */
const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 3,
      max: 20,
      message: '用户名长度应在3-20个字符之间',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' },
  ],
  sliderValue: [
    { required: true, message: '请完成滑块验证', trigger: 'change' },
    { validator: validateSlider, trigger: 'change' },
  ],
}

const loginFormRef = ref(null)

/**
 * @description 滑块验证函数
 * @param {Object} rule - 验证规则对象
 * @param {Number} value - 滑块值
 * @param {Function} callback - 回调函数
 */
function validateSlider(rule, value, callback) {
  if (value === 100) {
    callback()
  } else {
    callback(new Error('请将滑块滑到最右侧'))
  }
}

/**
 * @description 处理滑块变化
 * @param {Number} value - 滑块值
 */
const handleSliderChange = (value) => {
  if (value === 100) {
    ElMessage.success('验证成功')
  }
}

/**
 * @description 处理登录逻辑
 */
const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      let url = '/api/commonUsers/login'
      let data = { name: loginForm.name, password: loginForm.password }
      if (activeTab.value === 'admin') url = '/api/admins/login'
      if (activeTab.value === 'traffic') {
        url = '/api/managers/login'
        data = { userName: loginForm.name, password: loginForm.password }
      }
      const res = await request.post(url, data)
      if (res.code === 200) {
        ElMessage.success('登录成功')
        store.setUser(res.user || res.admin || res.manager)
        store.setToken(res.token || '')
        if (activeTab.value === 'admin') router.push('/admin')
        else if (activeTab.value === 'traffic') router.push('/traffic')
        else router.push('/usermap')
      } else {
        ElMessage.error(res.message || '登录失败')
      }
    }
  })
}

/**
 * @description 跳转到注册页面
 */
const goToRegister = () => {
  router.replace('/register')
}

const setActiveTab = (tab) => {
  activeTab.value = tab
  if (tab === 'common') {
    isDisabled.value = false
  } else {
    isDisabled.value = true
  }
}
</script>

<style lang="scss" scoped>
.login-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-image: url('/生成科技夜景图片.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;

  .login-card {
    width: 400px;
    background-color: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.18);
    .login-bar {
      display: flex;
      margin: 10px;
      .login-title {
        text-align: center;
        margin: 0;
        color: #b3b9c8;
        font-size: 22px;
        font-weight: 600;
        flex: 1;
        cursor: pointer;
      }
      .active {
        color: #409eff;
      }
    }

    .login-button {
      width: 100%;
    }

    .slider-container {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 0 10px;

      .slider-label {
        min-width: 80px;
        color: #606266;
        font-size: 14px;
      }

      :deep(.el-slider) {
        flex: 1;
        margin: 0;

        .el-slider__runway {
          margin: 8px 0;
        }
      }
    }

    .button-group {
      display: flex;
      gap: 20px;
      margin-top: 10px;
      width: 100%;
      .login-button,
      .register-button {
        flex: 1;
        height: 40px;
        font-size: 15px;
        border-radius: 4px;
        transition: all 0.3s ease;
      }

      .login-button {
        background: linear-gradient(to right, #409eff, #3a8ee6);
        border: none;
      }

      .register-button {
        background-color: #fff;
        border: 1px solid #dcdfe6;
        color: #606266;
      }
    }
  }
}
</style>
